import React, { useEffect, useState } from 'react';
import { Input, Modal, InputNumber, Button, Tooltip, Icon, Radio, message } from 'antd';
import cn from 'classnames';
import PropTypes from 'prop-types';
import _ from 'lodash';
import ScanDrawer from '../../../../add-task/components/scan-drawer';
import { addscanRate, editScanRate } from '@api/task';
import './index.less';

const PortManageModal = props => {
  const { modalVisible, changeModalVisible, getScanRateList, detail } = props;
  const [name, setName] = useState();
  const [nameError, setNameErro] = useState();
  // 最大连接并发配置
  const [connectionCountStatus, setConnectionCountStatus] = useState(1);
  // 最大连接数
  const [maxImumConnection, setMaxImumConnection] = useState(8);
  // 最大连接数错误提示
  const [connectionCountError, setConnectionCountError] = useState();
  // 连接数建议表
  const [drawerVisible, setDrawerVisible] = useState(false);
  // 扫描带宽
  const [scanBandwidth, setScanBandwidth] = useState(2000);
  // 扫描带宽报错
  const [scanBandwidthError, setScanBandwidthError] = useState('');
  // 扫描带宽选择按钮
  const [scanBandWidthStatus, setScanBandWidthStatus] = useState(1);

  const clearForm = () => {
    setNameErro('');
    setConnectionCountError('');
    setScanBandwidthError('');
    setName('');
    setMaxImumConnection(8);
    setScanBandwidth(2000);
    setConnectionCountStatus(1);
    setScanBandWidthStatus(1);
  };
  const onClickSubmit = () => {
    if (!name) {
      setNameErro('请输入名称');
      return;
    }
    if (name.length > 32) {
      setNameErro('不超过32个字符');
      return;
    }

    const api = detail ? editScanRate : addscanRate;
    let body = {
      name,
      maximumConnection: connectionCountStatus === 0 ? 0 : maxImumConnection,
      scanBandwidth: scanBandWidthStatus === 0 ? 0 : scanBandwidth
    };
    if (detail) {
      body.scanRateId = detail._id;
    }
    api({
      ...body
    })
      .then(() => {
        message.success(detail ? '修改成功' : '新增成功');
        getScanRateList();
        clearForm();
        changeModalVisible(false);
      })
      .catch(e => {
        message.error(e.message);
      });
  };
  const ChangeMaxImumConnection = value => {
    if (value < 1) {
      setConnectionCountError('配置参数不能小于1万');
      setMaxImumConnection(1);
    } else if (value > 500) {
      setConnectionCountError('配置参数不能大于500');
      setMaxImumConnection(500);
    } else {
      setConnectionCountError('');
    }
    setMaxImumConnection(value);
  };

  const ChangescanBandwidth = value => {
    let marker = false;
    if (value < 500) {
      setScanBandwidthError('扫描不能小于500万');
      marker = true;
    } else if (value > 50000) {
      setScanBandwidthError('配置参数不能大于50000');
      marker = true;
    } else {
      setScanBandwidthError('');
    }
    setScanBandwidth(marker ? 500 : value);
  };

  useEffect(() => {
    if (_.get(detail, '_id', '')) {
      const { name, maximumConnection, scanBandwidth } = detail;
      setName(name);
      if (maximumConnection === 0) {
        setConnectionCountStatus(0);
      } else {
        setConnectionCountStatus(1);
        setMaxImumConnection(maximumConnection);
      }
      if (scanBandwidth === 0) {
        setScanBandWidthStatus(0);
      } else {
        setScanBandWidthStatus(1);
        setScanBandwidth(scanBandwidth);
      }
    }
  }, [detail]);
  return (
    <div className="password-modal">
      <Modal
        maskClosable={false}
        title={<span style={{ fontWeight: 600 }}>{detail ? '修改' : '添加'}扫描速率模版</span>}
        className="port-manage-modal-modal"
        visible={modalVisible}
        width={580}
        portManage
        onCancel={() => {
          clearForm(), changeModalVisible(false);
        }}
        onOk={onClickSubmit}
        okButtonProps={{ className: 'button-forwards' }}
      >
        <>
          <div className="item">
            <span className="item-title required f14">名称</span>
            <Input
              placeholder="格式为中文、英文、特殊字符或数字，不超过32个字符"
              value={name}
              max={32}
              onChange={e => {
                if (e.target.value) {
                  setNameErro('');
                }
                setName(e.target.value);
              }}
            />
          </div>
          {nameError && <p className={'validate-error connection-error'}>{nameError}</p>}
          <div className={cn('item', 'connectionCount')}>
            <span className="item-title required f14">
              最大连接并发数
              <Tooltip
                title={
                  '请根据上层转发设备所能建立的最大连接数或者目标资产的处理性能来合理设置。设置的越小，任务执行的时间越长。范围：1万-500万，默认值：8万'
                }
              >
                <Icon className={'icon-question'} type="exclamation-circle" />
              </Tooltip>
            </span>
            <Radio.Group
              value={connectionCountStatus}
              style={{ display: 'flex' }}
              onChange={e => setConnectionCountStatus(e.target.value)}
            >
              <Radio value={0}>不限制</Radio>
              <Radio value={1}>自定义</Radio>
            </Radio.Group>
            {connectionCountStatus === 1 && (
              <>
                <InputNumber
                  value={maxImumConnection}
                  onChange={ChangeMaxImumConnection}
                  min={1}
                  max={500}
                  style={{ minWidth: 120 }}
                />
                <span className="unit">&nbsp;万</span>
                &nbsp;
                <Button
                  type="link"
                  size="small"
                  onClick={() => {
                    setDrawerVisible(true);
                  }}
                  className={'icon-exclamation'}
                >
                  连接数建议表
                </Button>
              </>
            )}
          </div>
          {connectionCountError && (
            <p className={'validate-error connection-error'}>{connectionCountError}</p>
          )}
          <div className={cn('item', 'speed-limit')}>
            <span className="item-title f14 required">
              扫描带宽
              <Tooltip title="实际扫描所产生流量会因探测目标和端口的数量而不同，您可在这里设置最大允许的扫描带宽。最大为50000Kbps">
                <Icon type="exclamation-circle" />
              </Tooltip>
            </span>
            <Radio.Group
              onChange={e => setScanBandWidthStatus(e.target.value)}
              value={scanBandWidthStatus}
            >
              <Radio value={0}>不限制</Radio>
              <Radio value={1}>自定义</Radio>
            </Radio.Group>
            {scanBandWidthStatus === 1 && (
              <span className="speed-limit-input">
                <InputNumber
                  min={500}
                  max={50000}
                  value={scanBandwidth}
                  style={{ width: 120 }}
                  onChange={ChangescanBandwidth}
                />
                <span className="unit">&nbsp;Kbps</span>
              </span>
            )}
          </div>
          {scanBandwidthError && (
            <p className={'validate-error connection-error'}>{scanBandwidthError}</p>
          )}
          <ScanDrawer
            drawerVisible={drawerVisible}
            closeDrawer={() => {
              setDrawerVisible(false);
            }}
          />
        </>
      </Modal>
    </div>
  );
};

PortManageModal.propTypes = {
  form: PropTypes.object.isRequired,
  changeModalVisible: PropTypes.function,
  modalVisible: PropTypes.boolean,
  getScanRateList: PropTypes.function,
  detail: PropTypes.object,
  isAddPort: PropTypes.boolean
};

export default PortManageModal;
